using System;
using System.Globalization;
using NPOI.SS.UserModel;

namespace PddWebAuto.Helper
{
    public static class ExcelHelper
    {
        /// <summary>
        /// 获取列的值
        /// </summary>
        /// <param name="Cell"></param>
        /// <returns></returns>
        public static string GetCellValue(ICell Cell)
        {
            if (Cell == null) return null;

            switch (Cell.CellType)
            {
                case CellType.Unknown:
                case CellType.Formula:
                case CellType.Blank:
                case CellType.Boolean:
                case CellType.Error:
                    return string.Empty;
                case CellType.Numeric:
                    return Cell.NumericCellValue.ToString(CultureInfo.InvariantCulture);
                case CellType.String:
                    return Cell.StringCellValue;
                default:
                    return string.Empty;
            }
        }

        /// <summary>
        /// 自动宽度
        /// </summary>
        /// <param name="sheet"></param>
        /// <param name="cnt"></param>
        public static void AutoColumnWidth(ISheet sheet, int cnt)
        {
            var rows = sheet.LastRowNum + 1;
            var cols = cnt + 1;
            var setWidth = false;
            for (var i = 0; i < rows; i++)
            {
                var row = sheet.GetRow(i);
                if (row == null) continue;
                for (var col = 0; col <= cols; col++)
                {
                    if (!setWidth)
                    {
                        sheet.SetColumnWidth(col, Convert.ToInt32(Math.Round(9.46 * 256,0)));
                    }
                    var cell = row.GetCell(col);
                    if (cell == null) continue;
                }
                setWidth = true;
            }
        }
    }
}